package net.tngou.jtdb.sql;


import java.io.IOException;
import java.io.StringReader;

import org.apache.commons.lang3.StringUtils;

import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.parser.CCJSqlParserManager;
import net.tngou.db.util.ResultSet;
import net.tngou.jtdb.netty.TngouClient;

public class Statement {

	TngouClient tngouClient = null;
	
	public Statement(TngouClient tngouClient) {
		this.tngouClient=tngouClient;
	}
	
	public ResultSet executeQuery(String sql) throws IOException, InterruptedException
	{
		
		if(tngouClient==null) return new ResultSet();
		ResultSet resultSet= tngouClient.exe(sql);
		return resultSet;
	}
	
	
	
	public ResultSet execute(String sql,String ... params) throws IOException, InterruptedException 
	{
		sql=StringUtils.replace(sql, "?", "$tngou#");
		for (String param : params) {
			param=StringUtils.replace(param, "'", "\"");
			sql=StringUtils.replace(sql, "$tngou#", "'"+param+"'", 1);
		}
		
	
		try {
			CCJSqlParserManager manager = new CCJSqlParserManager();
			manager.parse(new StringReader(sql));
			
		} catch (JSQLParserException e) {
			
			return new ResultSet();
//			e.printStackTrace();
		}
		
		if(tngouClient==null) return new ResultSet();
		ResultSet resultSet= tngouClient.exe(sql);
		return resultSet;
		  
		
	}
	
	
	
	
}
